import json

from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt

from app01 import models
from django.http import JsonResponse

# Create your views here.


def home(request):
    return render(request, 'home.html')


def book_list(request):
    book_queryset = models.Book.objects.all()
    return render(request, 'book_list.html', locals())


def book_add(request):
    if request.method == 'POST':
        book_dic = {
            'title': request.POST.get('title'),
            'price': request.POST.get('price'),
            'publish_date': request.POST.get('publish_date'),
            'publish_id': request.POST.get('publish'),

        }
        authors_list = request.POST.getlist('authors')
        print(book_dic)
        book_obj = models.Book.objects.create(**book_dic)  # 返回当前被创建的对象
        book_obj.authors.add(*authors_list)
        return redirect('book_list')
    # 获取当前仙童中所有的出版社信息和作者信息
    publish_queryset = models.Publish.objects.all()
    author_queryset = models.Author.objects.all()
    return render(request, 'book_add.html', locals())


def book_edit(request, edit_id):
    edit_obj = models.Book.objects.filter(pk=edit_id).first()
    publish_queryset = models.Publish.objects.all()
    author_queryset = models.Author.objects.all()
    if request.method == 'POST':
        book_dic = {
            'title': request.POST.get('title'),
            'price': request.POST.get('price'),
            'publish_date': request.POST.get('publish_date'),
            'publish_id': request.POST.get('publish'),
        }
        authors_list = request.POST.getlist('authors')
        book_obj = models.Book.objects.filter(pk=edit_id).update(**book_dic)
        print(book_obj)
        edit_obj.authors.set(authors_list)
        return redirect('book_list')
    return render(request, 'book_edit.html', locals())


def book_delete(request, del_id):
    models.Book.objects.filter(pk=del_id).delete()
    return redirect('book_list')


def book(request):
    return render(request, 'get_book.html')


@csrf_exempt
def get_all(request):
    print(request.POST.get('a'))
    print(json.loads(request.body), type(json.loads(request.body)))
    print(request.body.decode('utf-8'), type(request.body.decode('utf-8')))
    book_list = models.Book.objects.all()
    book_list_dic = [book.to_dict() for book in book_list]
    resp_data = {
        'status': 100,
        'msg': '成功',
        'data': book_list_dic,
    }
    return JsonResponse(resp_data)


#